#pragma once
#include "threadCache.h"
#include "pageCache.h"

static void* concurrentAlloc(size_t size) {
	if (size > MAX_SIZE) {
		size_t alignNum = alignSize::align(size);
		size_t index = alignNum >> PAGE_SHIFT;

		pageCache::getPageCache()->_pageMutex.lock();
		span* newSpan = pageCache::getPageCache()->fetchOfPage(index);
		newSpan->_size = size;
		pageCache::getPageCache()->_pageMutex.unlock();

		void* ptr = (void*)(newSpan->_pageId << PAGE_SHIFT);
		return ptr;
	}
	else {
		if (pTLSThreadCache == nullptr) {
			//pTLSThreadCache = new(threadCache);
			static Pool<threadCache> p;
			pTLSThreadCache = p.myNew();
		}

		//cout << std::this_thread::get_id() << ":" << pTLSThreadCache << endl;
		return pTLSThreadCache->allocate(size);
	}
}

static void concurrentFree(void* ptr) {
	span* backSpan = pageCache::getPageCache()->getSpanOfId(ptr);
	if (backSpan->_size > MAX_SIZE) {
		pageCache::getPageCache()->_pageMutex.lock();
		pageCache::getPageCache()->releasePageCache(backSpan);
		pageCache::getPageCache()->_pageMutex.unlock();
	}
	else {
		assert(pTLSThreadCache);
		pTLSThreadCache->dellocate(ptr, backSpan->_size);
	}
	
}